package com.jthinker.dao.impl;

import com.jthinker.base.ex.DBException;
import com.jthinker.dao.BaseDao;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chen.gang on 2014/11/22.
 */
@Component
public class BaseDaoImpl implements BaseDao
{

    @Resource
    private QueryRunner queryRunner;

    //map类型映射
    private ResultSetHandler<List<Map<String, Object>>> mapListHandler = new MapListHandler();

    @Override
    public List<Map<String, Object>> query(String sql, Object... params)
    {
        try
        {
            return queryRunner.query(sql, mapListHandler, params);
        }
        catch (SQLException e)
        {
            e.printStackTrace();
            throw new DBException(e);
        }
    }

    @Override
    public Map<String, Object> read(String sql, Object... params)
    {
        List<Map<String, Object>> list = query(sql, params);

        if (list == null || list.isEmpty())
        {
            return new HashMap<String, Object>(0);
        }

        return list.get(0);
    }

    @Override
    public int update(String sql, Object... params)
    {

        try
        {
            return queryRunner.update(sql, params);
        }
        catch (SQLException e)
        {
            e.printStackTrace();
            throw new DBException(e);
        }
    }

}
